package com.dhp.Utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class ExcelUtil {

    /**
     * excel文件处理
     * @param file
     * @return
     */

    public static String excelToCsv(MultipartFile file){
        try {
//            File file1 = ResourceUtils.getFile("classpath:test.xlsx");
            //读取文件内容
            List<Map<String , String>> data = EasyExcel.read(file.getInputStream()).excelType(ExcelTypeEnum.XLSX).sheet().headRowNumber(0).doReadSync();
            if (CollectionUtils.isEmpty(data)){
                log.error("表单数据为空");
                return "";
            }

            //取出表头 使用LinkedHashMap保持表头顺序
            StringBuilder AIChat = new StringBuilder();

            LinkedHashMap<String, String> dataMap = (LinkedHashMap<String, String>) data.get(0);
            List<String> dataList = dataMap.values().stream().filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());
            String header = StringUtils.join(dataList, ',') + '\n';
            AIChat.append(header);

            //取出数据
            for (int i = 1; i < data.size(); i++) {
                LinkedHashMap<String, String> realData = (LinkedHashMap<String, String>) data.get(i);
                List<String> realDataList = realData.values().stream().filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());
                String join = StringUtils.join(realDataList, ',') + '\n';
                AIChat.append(join);
            }

            String res = AIChat.toString();
            return res;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }



}
